<template>
	<div class="img-cropper">
		<div :class="['img-box', imageClass]"><img v-if="imgUrl != '' && imgUrl" :src="imgUrl" alt="" /></div>
		<input v-show="false" type="file" id="fileInput" @change="handleFileChange" name="file" ref="file" />
		<el-dropdown style="margin-top: 10px">
			<span class="el-dropdown-link">
				封面图设置
				<i class="el-icon-arrow-down el-icon--right"></i>
			</span>
			<el-dropdown-menu slot="dropdown">
				<el-dropdown-item icon="el-icon-upload2" v-if="showBtnByCode('upload')">
					<label for="fileInput" style="cursor: pointer; width: 90px; display: inline-block"><i aria-hidden="true">上传图片</i></label>
				</el-dropdown-item>
				<el-dropdown-item icon="el-icon-upload2" v-if="showBtnByCode('fromArticle')" @click.native="selectFromArticle">从正文中选择</el-dropdown-item>
				<el-dropdown-item icon="el-icon-upload2" v-if="showBtnByCode('fromNetDisk')" @click.native="selectFromNetDisk">从资源库中选择</el-dropdown-item>
				<el-dropdown-item icon="el-icon-circle-close" v-if="showBtnByCode('cancel')" @click.native="deleteImg">取消图片</el-dropdown-item>
			</el-dropdown-menu>
		</el-dropdown>
		<Cropper @e-emit="setImgInfo" :props="{ type: props.type }" />
		<SelectImgFromArticle :content="content" @e-emit="setSelectImgInfo" />
		<SelectImgFromNetDisk @emit="handleEmit" />
	</div>
</template>
<script>
import { tbSysAttachmentUpload } from '@/api/http';
import webinfo from '@/mixins/webinfo.js';
export default {
	mixins: [webinfo],
	components: {
		Cropper: () => import('./cropper.vue'),
		SelectImgFromArticle: () => import('./selectImgFromArticle.vue'),
		SelectImgFromNetDisk: () => import('@/views/module/netDisk/selectFile/index.vue')
	},
	data() {
		return {
			imgUrl: '',
			fileName: '',
			content: ''
		};
	},
	props: ['props'],
	//props{
	//defaultValue: null, //默认图片
	//type: 1, //1. 文章封面 2. 书籍封面
	//button: ['upload', 'fromArticle', 'fromNetDisk', 'cancel'],
	//1.upload 上传 2.fromArticle 从正文选择 3.fromNetDisk 从资源库选择 4.cancel 取消图片
	//}
	computed: {
		showBtnByCode() {
			return (code) => {
				return this.props.button.includes(code);
			};
		},
		imageClass() {
			switch (this.props.type) {
				case 1:
					return 'article-cover';
					break;
				case 2:
					return 'journal-cover';
					break;
				case 3:
					return 'avatar-cover';
					break;
				default:
					return 'avatar-cover';
					break;
			}
		}
	},
	watch: {
		'props.defaultValue': {
			immediate: true,
			handler(val) {
				let { type } = this.props;
				let baseImgUrl = type == 1 ? this.articleImg : this.journalImg;
				var imgUrl = val || baseImgUrl;
				if (imgUrl == '--') {
					imgUrl = '';
				}
				this.imgUrl = imgUrl;
			}
		}
	},
	mounted() {
		console.log(this.imageClass);
	},
	methods: {
		handleFileChange(e) {
			let file = e.target.files;
			this.fileName = file[0].name;
			if (!/\.(gif|jpg|jpeg|webp|png|GIF|JPG|PNG)$/.test(this.fileName)) {
				this.warnMsg('图片类型必须是.gif,jpeg,jpg,png.webp中的一种');
				this.fileName = '';
				return;
			}
			var reader = new FileReader(); //是一种异步文件读取
			reader.readAsDataURL(file[0]); //转换成base64 //数据读取完成触发
			reader.onload = (e) => {
				this.$bus.$emit('showCropperDialog', e.target.result);
			};
		},
		setImgInfo(v) {
			this.imgUrl = v;
			this.upload();
		},
		setSelectImgInfo(v) {
			if (typeof v === 'object') {
				this.imgUrl = v.httpUrl;
			} else {
				this.imgUrl = v;
			}
			this.$emit('e-emit', v);
		},
		deleteImg() {
			let { type } = this.props;
			this.imgUrl = type == 1 ? this.articleImg : this.journalImg;
			this.$emit('e-emit', { id: '', attrAddr: '', httpUrl: '' });
		},
		//从正文选图片
		selectFromArticle() {
			this.$emit('fatherMethod');
			this.$bus.$emit('selectImgFromArticle', this.content);
		},
		//获取父组件正文内容
		getContent(val) {
			this.content = val;
		},
		selectFromNetDisk() {
			this.$bus.$emit('selectFile', { showType: 1 });
		},
		handleEmit(v) {
			this.setSelectImgInfo(v[0]);
		},
		// 上传点击保存
		upload() {
			if (!this.imgUrl && this.imgUrl == '') return;
			const optionImg = this.base64toFile(this.imgUrl);
			const formData = new FormData();
			formData.append('file', optionImg);
			tbSysAttachmentUpload(formData).then((res) => {
				let imgInfo = res.data.data[0];
				this.$emit('e-emit', imgInfo);
			});
		},
		base64toFile(dataurl) {
			let arr = dataurl.split(',');
			let mime = arr[0].match(/:(.*?);/)[1];
			let suffix = mime.split('/')[1];
			let bstr = atob(arr[1]);
			let n = bstr.length;
			let u8arr = new Uint8Array(n);
			while (n--) {
				u8arr[n] = bstr.charCodeAt(n);
			}
			let newFileName = this.fileName.split('.');
			newFileName = this.fileName.replace(newFileName[newFileName.length - 1], '');
			return new File([u8arr], `${newFileName}${suffix}`, {
				type: mime
			});
		}
	}
};
</script>
<style scoped lang="scss">
.img-cropper {
	position: relative;
	width: 210px;
	text-align: center;
	.img-box {
		width: 100%;
		border: 1px dashed #ccc;
		border-radius: 5px;
		padding: 6px;
		overflow: hidden;
		box-sizing: border-box;
		img {
			display: block;
			width: 100%;
			height: 100%;
			border-radius: 3px;
		}
		&.article-cover {
			height: 140px;
		}
		&.journal-cover {
			height: 280px;
		}
		&.avatar-cover {
			height: 210px;
		}
	}
	.upload-btn {
		margin-top: 10px;
	}
}
</style>
